package org.mybatis.generator.codegen.mybatis3.xmlmapper.elements;

import java.util.Iterator;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities;
import org.mybatis.generator.internal.util.CollectionUtils;

/**
 * 生成带别名表字段，用于联查
 * 
 * @author tangdelong
 * 2015年12月1日
 */
public class Column2ElementGenerator extends AbstractXmlElementGenerator {

	@Override
	public void addElements(XmlElement parentElement) {
		 XmlElement answer = new XmlElement("sql"); 

	        answer.addAttribute(new Attribute("id","column2"));

	        context.getCommentGenerator().addComment(answer);

	        StringBuilder sb = new StringBuilder();
	        Iterator<IntrospectedColumn> iter = introspectedTable.getNonBLOBColumns().iterator();
	        while (iter.hasNext()) {
	        	sb.append(introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime());
	        	sb.append(".");
	            sb.append(MyBatis3FormattingUtilities.getSelectListPhrase(iter.next()));

	            if (iter.hasNext()) {
	                sb.append(", "); //$NON-NLS-1$
	            }

	            if (sb.length() > 80) {
	                answer.addElement(new TextElement(sb.toString()));
	                sb.setLength(0);
	            }
	        }
	        
	        // blob类型字段
	        Iterator<IntrospectedColumn> iterBlob = introspectedTable.getBLOBColumns().iterator();
	        boolean flag = true;
	        while (iterBlob.hasNext()) {
	        	if(CollectionUtils.isNotEmpty(introspectedTable.getNonBLOBColumns()) && flag){
	        		sb.append(", ");
	        		flag = false;
	        	}
	        	
	        	sb.append(introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime());
	        	sb.append(".");
	            sb.append(MyBatis3FormattingUtilities.getSelectListPhrase(iterBlob.next()));

	            if (iterBlob.hasNext()) {
	                sb.append(", "); //$NON-NLS-1$
	            }

	            if (sb.length() > 80) {
	                answer.addElement(new TextElement(sb.toString()));
	                sb.setLength(0);
	            }
	        }
	        

	        if (sb.length() > 0) {
	            answer.addElement((new TextElement(sb.toString())));
	        }

	        if (context.getPlugins().sqlMapBaseColumnListElementGenerated(
	                answer, introspectedTable)) {
	            parentElement.addElement(answer);
	        }

	}

}
